// pages/my/my.js
//获取应用实例
// const app = ;
const utils = require('../../utils/util');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLogin:false,
    userInfo:{},
    isBindPhone:false
  },

  login(){
    if (this.data.isLogin) return;
    var that = this;
    wx.getUserProfile({
      desc: '用户授权',
     async success(res){
        const data = await utils.wechartLogin();
        getApp().globalData.userInfo = Object.assign(data,res.userInfo);
        //将用户信息保存至本地缓存
        wx.setStorageSync('userInfo', JSON.stringify(getApp().globalData.userInfo));
        that.setData({
          userInfo: getApp().globalData.userInfo,
          isBindPhone: getApp().globalData.userInfo.phone ? false : true,
          isLogin:true
        })
      }
    })
  },
  
  onLoad:function(){
    this.setData({
      userInfo: getApp().globalData.userInfo || JSON.parse(wx.getStorageSync('userInfo'))
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onToOpinion:function(e){ 
    wx.navigateTo({
      url: '/pages/opinion/index',
    })
  },
  toNews:function(event){
    const {news_id,img_src} = event.target.dataset;
    wx.navigateTo({
      url: `/pages/about/index?news_id=${news_id}&img_src=${img_src}`
    })
  },
  toMyTestPaper:function (e) {
    this.goTo('/pages/myTestPaper/myTestPaper');
  },
  toMyVideo:function (e) {
    this.goTo('/pages/myVideo/myVideo');
  }
  ,
  toMyOrders:function () {
    this.goTo('/pages/myOrder/myOrder')
  },
  
  goTo(url){
    if (getApp().globalData.userInfo.token) {
        wx.navigateTo({ url })
      }else{
        wx.showToast({
            title: '请登录！',
            icon: 'success',
            duration: 3000
        })
      }
  },
 async getPhoneNumber (e) {
   const { avatarUrl , nickName , unionid } = getApp().globalData.userInfo;
   const {data} = await utils.request('GET','/wechat/bindPhone',{ avatarUrl , nickName , unionid , code:e.detail.code })
   getApp().globalData.userInfo.phone = data;
    this.setData({
      isBindPhone:false,
      userInfo:getApp().globalData.userInfo
    })
    wx.showToast({
      title: '绑定成功！',
      icon: 'success',
      duration: 3000
  })
  }
})